package com.hpe.fastfood.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.hpe.fastfood.pojo.Bussiness;
import com.hpe.fastfood.pojo.Commodity;
import com.hpe.fastfood.pojo.Type;
import com.hpe.fastfood.service.BussinessService;
import com.hpe.fastfood.service.CommodityService;
import com.hpe.fastfood.service.OrderService;
import com.hpe.fastfood.service.TypeService;
import com.hpe.fastfood.util.Page;
import com.hpe.fastfood.vo.CommodityVo;

/**
 * @ClassName: BussinessController
 * @Description:TODO 商户的controller
 * @author: fuchong
 * @date: 2018年11月23日 下午2:24:12
 */
@Controller
@RequestMapping("bussiness")
public class BussinessController {

	private static final String path = "D:/Workspaces/upload/";// 文件保存路径

	@Autowired
	private CommodityService commodityService;

	@Autowired
	private BussinessService bussinessService;

	@Autowired
	private OrderService orderService;

	@Autowired
	private TypeService typeService;

	/**
	 * @Description:TODO 跳到商户主页面
	 * @author: fuchong
	 * @date: 2018年11月23日 下午3:23:14
	 * @return
	 */
	@RequestMapping(value = "toBussiness")
	public String toIndex() {
		return "bussiness/index";
	}

	/**
	 * @Description:TODO查询所有商品
	 * @author: dwx
	 * @date: 2018年11月23日 上午10:32:26
	 * @param req
	 *            /**
	 * @Description:TODO 查询所有商品信息
	 * @author: fuchong
	 * @date: 2018年11月23日 下午2:23:26
	 * @param page
	 * @param foodName
	 * @return
	 */
	@RequestMapping(value = "selectCommodityByName")
	public ModelAndView selectCommodityByName(HttpServletRequest req, Page page, String foodName) {
		ModelAndView mv = new ModelAndView();
		try {
			Bussiness bussiness = (Bussiness) req.getSession().getAttribute("loginBussiness");
			page = commodityService.selectCommodityByName(page, foodName, bussiness.getBussinessId());
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		mv.addObject("page", page);
		mv.addObject("foodName", foodName);
		mv.setViewName("bussiness/shoplist");
		return mv;
	}

	/**
	 * @Description:TODO 跳到添加商品页面
	 * @author: fuchong
	 * @date: 2018年11月23日 下午3:23:56
	 * @return
	 */
	@RequestMapping(value = "addCommodityPage")
	public ModelAndView addCommodityPage() {
		ModelAndView mv = new ModelAndView();
		List<Type> type = null;
		try {
			type = typeService.selectTypeInfo();
		} catch (Exception e) {
			// TODO: handle exception
			e.getMessage();
		}
		mv.addObject("type", type);
		mv.setViewName("bussiness/shop_add");
		return mv;
	}

	/**
	 * @Description:TODO 添加商品
	 * @author: fuchong
	 * @date: 2018年11月23日 下午3:24:37
	 * @return
	 * @throws IOException
	 * @throws IllegalStateException
	 */
	@RequestMapping(value = "addCommodity", method = RequestMethod.POST)
	public String addCommodity(String foodName, Integer typeId, double foodPrice, String foodBrief,
			@RequestParam(value = "foodPicture") MultipartFile file, HttpServletRequest request)
			throws IllegalStateException, IOException {
		Bussiness bussiness = (Bussiness) request.getSession().getAttribute("loginBussiness");
		// 上传图片
		// 获取上传文件的原始名称
		String org_filename = file.getOriginalFilename();
		// 获取main 类型
		String extc = FilenameUtils.getExtension(org_filename);
		// 设置上传文件的保存目录
		System.err.println(path);
		File filePath = new File(path);
		// 如果保存文件的地址不存在，就先创建目录
		if (!filePath.exists()) {
			filePath.mkdirs();
		}
		// 使用UUID进行重命名
		String new_filename = UUID.randomUUID() + "." + extc;
		System.err.println(new_filename);
		// 使用MultipartFile 接口的方法 完成上传到指定位置
		file.transferTo(new File(path + "/" + new_filename));

		// 上传商品信息
		Commodity commodity = new Commodity();
		commodity.setFoodBrief(foodBrief);
		commodity.setFoodName(foodName);
		commodity.setFoodPrice(foodPrice);
		commodity.setTypeId(typeId);
		commodity.setBussinessId(bussiness.getBussinessId());
		commodity.setFoodPicture(new_filename);
		commodity.setFoodSale(0);// 销售量
		commodity.setState(1);// 商品启用
		try {
			commodityService.addCommodity(commodity);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:/bussiness/selectCommodityByName";
	}

	/**
	 * @Description:TODO 跳转到修改页面
	 * @author: fuchong
	 * @date: 2018年11月23日 下午3:26:10
	 * @return
	 */
	@RequestMapping(value = "updateCommodityPage")
	public ModelAndView updateCommodityPage(int foodId) {
		ModelAndView mv = new ModelAndView();
		CommodityVo commodity = null;
		List<Type> type = null;
		try {
			type = typeService.selectTypeInfo();// 查询商品种类
			commodity = commodityService.selectCommodityById(foodId);// 查询商品信息
		} catch (Exception e) {
			// TODO: handle exception
			e.getMessage();
		}
		mv.addObject("type", type);
		mv.addObject("commodity", commodity);
		mv.setViewName("bussiness/shop_update");
		return mv;
	}

	/**
	 * @Description:TODO 修改商品信息
	 * @author: fuchong
	 * @date: 2018年11月23日 下午3:26:25
	 * @return
	 * @throws IOException
	 * @throws IllegalStateException
	 */
	@RequestMapping(value = "updateCommodity", method = RequestMethod.POST)
	public String updateCommodity(Integer foodId, String foodName, Integer typeId, double foodPrice, String foodBrief,
			@RequestParam(value = "foodPicture") MultipartFile file, HttpServletRequest request)
			throws IllegalStateException, IOException {
		// 上传图片
		// 获取上传文件的原始名称
		String org_filename = file.getOriginalFilename();
		// 获取main 类型
		String extc = FilenameUtils.getExtension(org_filename);
		// 设置上传文件的保存目录
		System.err.println(path);
		File filePath = new File(path);
		// 如果保存文件的地址不存在，就先创建目录
		if (!filePath.exists()) {
			filePath.mkdirs();
		}
		// 使用UUID进行重命名
		String new_filename = UUID.randomUUID() + "." + extc;
		System.err.println(new_filename);
		// 使用MultipartFile 接口的方法 完成上传到指定位置
		file.transferTo(new File(path + "/" + new_filename));

		// 上传商品信息
		Commodity commodity = new Commodity();
		commodity.setFoodId(foodId);
		commodity.setFoodBrief(foodBrief);
		commodity.setFoodName(foodName);
		commodity.setFoodPrice(foodPrice);
		commodity.setTypeId(typeId);
		commodity.setFoodPicture(new_filename);
		try {
			commodityService.updateCommodity(commodity);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:/bussiness/selectCommodityByName";
	}

	/**
	 * @Description:TODO 查看个人信息
	 * @author: fuchong
	 * @date: 2018年11月23日 下午2:23:55
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "selectBussiness")
	public ModelAndView selectBussiness(HttpServletRequest req) {
		ModelAndView mv = new ModelAndView();
		Bussiness bussiness = (Bussiness) req.getSession().getAttribute("loginBussiness");
		try {
			bussiness = bussinessService.selectBussinessById(bussiness.getBussinessId());
		} catch (Exception e) {
			// TODO: handle exception
		}
		mv.addObject("bussiness", bussiness);
		mv.setViewName("bussiness/bussinesslist");
		return mv;
	}

	/**
	 * @Description:TODO 修改个人信息
	 * @author: fuchong
	 * @date: 2018年11月23日 下午2:27:37
	 * @return
	 */
	@RequestMapping(value = "updateBussiness", method = RequestMethod.POST)
	public String updateBussiness(Bussiness bussiness) {
		try {
			bussinessService.updateBussiness(bussiness);
		} catch (Exception e) {
			// TODO: handle exception
			e.getMessage();
		}
		return "redirect:/bussiness/selectBussiness";
	}

	/**
	 * @Description:TODO 查询订单信息
	 * @author: fuchong
	 * @date: 2018年11月23日 下午5:08:25
	 * @return
	 */
	@RequestMapping(value = "selectOrder")
	public ModelAndView selectOrder(Page page) {
		ModelAndView mv = new ModelAndView();
		try {
			page = orderService.selectOrder(page);
		} catch (Exception e) {
			// TODO: handle exception
		}
		mv.addObject("page", page);
		mv.setViewName("bussiness/order");
		return mv;
	}

	/**
	 * @Description:TODO 图片查询
	 * @author: fuchong
	 * @date: 2018年11月23日 下午7:33:08
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "show")
	public void showImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.setContentType("text/html; charset=UTF-8");
		response.setContentType("image/jpeg");
		String fname = request.getParameter("foodPicture");
		String newpath = new String(fname.getBytes("ISO-8859-1"), "UTF-8");
		String absolutePath = path + newpath;
		FileInputStream fis = new FileInputStream(absolutePath);
		OutputStream os = response.getOutputStream();
		try {
			int count = 0;
			byte[] buffer = new byte[1024 * 1024];
			while ((count = fis.read(buffer)) != -1)
				os.write(buffer, 0, count);
			os.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (os != null)
				os.close();
			if (fis != null)
				fis.close();
		}
	}

	/**
	 * @Description:TODO 逻辑删除
	 * @author: fuchong
	 * @date: 2018年11月25日 下午3:34:33
	 * @param foodId
	 * @return
	 */
	@RequestMapping(value = "changeCommodity")
	public String changeCommodity(int foodId) {
		Commodity commodity = new Commodity();

		commodity = commodityService.selectCommodityById(foodId);
		if (commodity.getState() % 2 == 1) {
			commodity.setState(0);
		} else {
			commodity.setState(1);
		}

		try {
			commodityService.changeCommodity(commodity);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "redirect:/bussiness/selectCommodityByName";
	}

}
